import AddIcon from '@mui/icons-material/Add'
import { gridSpacing, ButtonConfig } from '@/store/constant'
import { addShift, editShift, deleteShift } from '@/api/index'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import duration from 'dayjs/plugin/duration'
import { ChangeEvent } from 'react'
dayjs.extend(duration)
dayjs.extend(customParseFormat)

const defaultFormData = {
  shift_id: '',
  start_delta: 0,
  end_delta: 0
}
const handlerConfig = {
  add: addShift,
  edit: editShift,
  delete: deleteShift
}

interface Props {
  refresh: () => void
  type?: string
  renderTrigger?: (props: any) => JSX.Element
  record?: any
}
const FormConfig = [
  { label: '开始时间', key: 'start_delta' },
  { label: '结束时间', key: 'end_delta' }
]
// ---增删改---排班功能按钮
const ShiftButton = ({ refresh, type = 'add', renderTrigger, record }: Props) => {
  const { label } = get(ButtonConfig, [type])
  const isDelete = type === 'delete'
  const [open, setOpen] = useState(false)
  const { run, loading } = useRequest(get(handlerConfig, [type]), {
    manual: true,
    onSuccess() {
      refresh()
      setOpen(false)
      setFormData({ ...defaultFormData })
    }
  })
  const [formData, setFormData] = useState({ ...defaultFormData })
  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }

  const handleChangeTime = (type: string) => (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const value = e.target.value
    const targetTime = dayjs(value, 'HH:mm')
    const startTime = dayjs().startOf('day')
    setFormData({ ...formData, [type]: targetTime.diff(startTime) })
  }

  const disabled = isEmpty(formData.shift_id)
  const handleConfirm = () => {
    const { end_delta, start_delta } = formData
    // 跨天需要+1d
    const data = { ...formData, end_delta: end_delta < start_delta ? end_delta + dayjs.duration({ d: 1 }) : end_delta }
    run(isDelete ? pick(data, ['id']) : data)
  }

  useEffect(() => {
    if (record) {
      setFormData({ ...record })
    }
  }, [record])
  return (
    <>
      {renderTrigger ? (
        renderTrigger({ onClick: handleOpen })
      ) : (
        <Button onClick={handleOpen} variant="outlined" size="small" color="secondary" startIcon={<AddIcon />}>
          {label}
        </Button>
      )}
      <Dialog open={open} onClose={handleClose}>
        <DialogTitle fontSize="1rem">{label}班次</DialogTitle>
        <DialogContent>
          <Grid container spacing={gridSpacing}>
            <Grid item xs={12}>
              <TextField
                required
                value={formData.shift_id}
                fullWidth
                margin="dense"
                autoFocus
                id="shift_id"
                label="班次名称"
                type="text"
                onChange={(e) => setFormData({ ...formData, shift_id: e.target.value })}
                disabled={isDelete}
              />
            </Grid>
            <Grid item container spacing={gridSpacing}>
              {FormConfig.map((cell) => {
                return (
                  <Grid item xs={6} key={cell.key}>
                    <TextField
                      required
                      value={dayjs.duration(get(formData, [cell.key])).format('HH:mm')}
                      fullWidth
                      margin="dense"
                      id={cell.key}
                      type="time"
                      label={cell.label}
                      onChange={handleChangeTime(cell.key)}
                      disabled={isDelete}
                    />
                  </Grid>
                )
              })}
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            Cancel
          </Button>
          <LoadingButton
            loading={loading}
            disabled={disabled}
            variant="contained"
            color={type === 'delete' ? 'error' : 'secondary'}
            onClick={handleConfirm}
          >
            Confirm
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default ShiftButton
